package com.heatup.apt.api.controller;

import com.heatup.apt.api.controller.pay.util.PropertiesUtil;
import com.heatup.apt.api.service.*;
import com.heatup.apt.common.constants.ErrorCodeConstants;
import com.heatup.apt.common.constants.UserConstants;
import com.heatup.apt.common.constants.UserProductServiceConstants;
import com.heatup.apt.common.dao.redis.UserPositionRedisDao;
import com.heatup.apt.common.dao.user.UserDiscountMapper;
import com.heatup.apt.common.util.*;
import com.heatup.apt.model.api.ApiResultModel;
import com.heatup.apt.model.company.CompanyInfo;
import com.heatup.apt.model.company.CompanyStaff;
import com.heatup.apt.model.order.OrderFinished;
import com.heatup.apt.model.user.UserDiscount;
import com.heatup.apt.model.user.UserInfo;
import com.heatup.apt.model.user.UserProductService;
import com.mysql.jdbc.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by liuwanfen on 16/8/19.
 */
@Controller
@RequestMapping("/user")
public class UserController extends BaseController {

    private static final Logger logger = LoggerFactory.getLogger(UserController.class);

    @Resource
    private UserService userService;

    @Resource
    private CourseSignService courseSignService;

    @Resource
    private ProductServiceInterface productService;

    @Resource
    private OrderService orderService;

    @Resource
    private UserCommentService userCommentService;

    @Resource
    private UserDiscountMapper userDiscountMapper;

    @Resource
    private CompanyInfoService companyInfoService;

    @Resource
    private CompanyStaffService companyStaffService;
    
    @Resource
	private UserPositionRedisDao userPositionRedisDao;
    
    @Resource 
    private UserProductServiceService userProductServiceService;
    
    private String hasRequest = String.valueOf(PropertiesUtil.get("has_request")).trim();

    @ResponseBody
    @RequestMapping(value = "/login", method = {RequestMethod.POST, RequestMethod.GET})
    private String login(HttpServletRequest request) {
        String username = RequestTools.RequestString(request, "username", "");
        String password = RequestTools.RequestString(request, "password", "");
        String callback = RequestTools.RequestString(request, "callback", "");

        int userId = RequestTools.RequestInt(request, "userId", -1);


        ApiResultModel<Object> apiResultModel = new ApiResultModel<Object>();
        logger.info(" login | hasRequest"+hasRequest);

        // userService.updateUserLevel(userId);

        //临时登录
        UserInfo userInfo = userService.selectById(userId);
        if (userInfo != null) {
            this.setUserId(userId);
            this.setUserInfo(userInfo);
            apiResultModel.setLogined(this.isLogined());
            apiResultModel.setRet(ApiResultModel.RET_SUCCESS);
            apiResultModel.setMsg("登录成功");

        } else {
            apiResultModel.setLogined(this.isLogined());
            apiResultModel.setRet(ApiResultModel.RET_ERROR);
            apiResultModel.setMsg("登录失败");
        }

        return ResponseTools.CallBackResultJsonP(JsonTools.jsonSer(apiResultModel), callback);
    }

    @ResponseBody
    @RequestMapping(value = "/info", method = {RequestMethod.POST, RequestMethod.GET})
    private String getUserInfo(HttpServletRequest request) {
        Integer userId = this.getUserId();
        String callback = RequestTools.RequestString(request, "callback", "");
        ApiResultModel<Map<String, Object>> apiResultModel = new ApiResultModel<Map<String, Object>>();


        //未登陆
        if (!isLogined()) {
            apiResultModel.setRet(ApiResultModel.RET_ERROR);
            apiResultModel.setErrorCode(ErrorCodeConstants.Code.USER_NOT_LOGIN.getCode());
            apiResultModel.setMsg(ErrorCodeConstants.Code.USER_NOT_LOGIN.getMessage());
            return ResponseTools.CallBackResultJsonP(JsonTools.jsonSer(apiResultModel), callback);
        }

        Map<String, Object> map = new HashMap<String, Object>();
        UserInfo user = userService.getUserInfoById(userId);
//        UserProductService userProductService = userProductServiceService.queryUserProductServiceByUserIdAndType(userId, UserProductServiceConstants.SELFTYPESERVICE);
        Integer hasYearCardService = userProductServiceService.checkUserHasYearCardService(user.getId());
        UserDiscount userDiscount = userDiscountMapper.selectById(1);
        boolean isBlacklist = userService.checkUserIsBlacklistUser(userId);
        if (user != null) {
            map.put("userid", user.getId());
            map.put("nickname", user.getNickName());
            map.put("mobile", user.getMobile());
            map.put("headimg", user.getHeadImg());
            map.put("level", user.getLevel());
            map.put("hasMobile", (!StringUtils.isNullOrEmpty(user.getMobile())));
            map.put("isSubScribe", user.getSubscribe() != null && user.getSubscribe() == 1 ? "true" : "false");
            map.put("dateLin", DateUtils.format(userDiscount.getDateline(), "yyyy-MM-dd"));
            map.put("isBlacklist", isBlacklist);
            map.put("isHasSelfService", hasYearCardService);
        	map.put("hasYearCardService", hasYearCardService);
            //查询用户是否已绑定企业储值卡
            CompanyStaff companyStaff = new CompanyStaff();
            companyStaff.setUserId(userId);
            companyStaff.setStatus(0);
            companyStaff = companyStaffService.selectOne(companyStaff);
            if (companyStaff != null 
            		&& companyStaff.getId() != null 
            		&& companyStaff.getId() > 0) {
                //校验公司是否有效
                CompanyInfo companyInfo = companyInfoService.selectById(companyStaff.getCompanyId());
                if (companyInfo != null && companyInfo.getStatus() == 1) {
                    map.put("isBindingCompanyValuedCard", true);
                } else {
                    map.put("isBindingCompanyValuedCard", false);
                }
            } else {
                map.put("isBindingCompanyValuedCard", false);
            }

            try {
                DesUtils des = new DesUtils(String.valueOf(PropertiesUtil.get("des_key")).trim());
                map.put("openid", des.encrypt(user.getOpenid()));
            } catch (Exception e) {
                e.printStackTrace();
                logger.info(e.getMessage() + e.getCause());
            }

            OrderFinished orderFinished = orderService.queryUserLeasonsCount(userId);
            int courseCount = 0;
            int courseMins = 0;
            if (orderFinished != null && orderFinished.getCourseCount() != null) {
                courseCount = orderFinished.getCourseCount();
            }
            if (orderFinished != null && orderFinished.getCourseMins() != null) {
                courseMins = orderFinished.getCourseMins();
            }
            map.put("courseCount", courseCount);
            map.put("courseMins", courseMins);


            apiResultModel.setRet(ApiResultModel.RET_SUCCESS);
            apiResultModel.setMsg("");
            apiResultModel.setLogined(true);
            apiResultModel.setData(map);

        } else {
            apiResultModel.setRet(ApiResultModel.RET_ERROR);
            apiResultModel.setErrorCode(ErrorCodeConstants.Code.USER_NOT_FIND.getCode());
            apiResultModel.setMsg(ErrorCodeConstants.Code.USER_NOT_FIND.getMessage());
        }
        apiResultModel.setLogined(this.isLogined());
        return ResponseTools.CallBackResultJsonP(JsonUtils.toJsonStr(apiResultModel), callback);
    }

    /**
     * 会员信息
     *
     * @param callback
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/vipinfo", method = {RequestMethod.POST, RequestMethod.GET})
    private String getVipInfo( String callback,Integer productId,String longitudeLatitude) {

        Integer userId = this.getUserId();
        
        ApiResultModel<Map<String, Object>> apiResultModel = new ApiResultModel<>();
        if(productId == null){
        	productId = 1;
        }

        //未登陆
        if (userId == null) {
            apiResultModel.setRet(ApiResultModel.RET_ERROR);
            apiResultModel.setMsg(ErrorCodeConstants.Code.USER_NOT_LOGIN.getMessage());
            apiResultModel.setErrorCode(ErrorCodeConstants.Code.USER_NOT_LOGIN.getCode());
            return ResponseTools.CallBackResultJsonP(JsonTools.jsonSer(apiResultModel), callback);
        }

        //会员价格数据
        Map<String, Object> resultMap = userService.getVipInfoById(userId,productId,longitudeLatitude);

        //查询用户是否有绑定企业储值卡 且 企业有效 企业员工有效 才返回
        CompanyStaff companyStaff = companyStaffService.selectCompanyPaymentDetailByUserId(userId);
        if(companyStaff != null && companyStaff.getId() != null){
        	if (companyStaff.getIsBuyTypeLimit().equals(1) 
            		|| companyStaff != null && companyStaff.getIsBuyTypeLimit() == 0 && companyStaff.getLimitVip().equals(1)
                    ) {
                resultMap.put("companyStaff", companyStaff);

            }
        }

        apiResultModel.setData(resultMap);
        apiResultModel.setRet(ApiResultModel.RET_SUCCESS);
        apiResultModel.setMsg("");

        apiResultModel.setLogined(this.isLogined());
        return ResponseTools.CallBackResultJsonP(JsonUtils.toJsonStr(apiResultModel), callback);
    }


    /**
     * 用户评论
     *
     * @param courseId 课程ID
     * @param comment  评论
     * @param callback 回调
     * @return
     */
    public String addCourseComment(Integer courseId, String comment, String callback) {

        ApiResultModel apiResultModel = new ApiResultModel(isLogined());

        try {
            // userCommentService.addCourseComment(courseId, comment);


        } catch (Exception e) {
            logger.error("用户添加评论出错 blank - -! --->" + e + e.getCause());
        }
        return ResponseTools.CallBackResultJsonP(JsonTools.jsonSer(apiResultModel), callback);
    }

    /**
     * 签到测试方法
     *
     * @param courseId 课程 ID
     * @return object
     */
    @RequestMapping(value = "/signInTest")
    @ResponseBody
    public Object signInTest(@RequestParam Integer courseId) {

        UserInfo userInfo = getUserInfo();
        try {
            return courseSignService.courseCoachUserSign(courseId, userInfo.getOpenid());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    
    /**
     * 获取用户地理位置的经纬度信息
     * @param request
     * @param response
     * @return
     */
    @ResponseBody
    @RequestMapping("/get_user_position")
    public String getUserPositionIsNow(HttpServletRequest request, HttpServletResponse response){
    	ApiResultModel<Object> apiResultModel = new ApiResultModel<Object>(isLogined());
    	String callback = RequestTools.RequestString(request, "callback", "");
    	
    	
    	Map<String,Object> map = null;
    	try {
    		UserInfo userInfo = this.getUserInfo();
    		if(userInfo == null){
    			apiResultModel.setRet(apiResultModel.RET_SUCCESS);
        		apiResultModel.setErrorCode(apiResultModel.RET_SUCCESS);
        		apiResultModel.setLogined(this.isLogined());
        		apiResultModel.setData(map);
        		apiResultModel.setMsg("用户未登录");
        		logger.info("======================================get_user_position:用户未登录=====================================");
        		return ResponseTools.CallBackResultJsonP(JsonTools.jsonSer(apiResultModel), callback);
    		}
    		String openid =userInfo.getOpenid();
    		logger.info("============openid :"+openid);
    		map =  userPositionRedisDao.queryUserPosition(userInfo);//request.getSession().getAttribute(openid);
    		logger.info("============obj :"+map);
    		if(map == null){
        		apiResultModel.setRet(apiResultModel.RET_SUCCESS);
        		apiResultModel.setErrorCode(apiResultModel.RET_SUCCESS);
        		apiResultModel.setLogined(this.isLogined());
        		apiResultModel.setData("");
        		apiResultModel.setMsg("获取不到用户的地理位置");
        		logger.info("====================getUserPositionIsNow: not get user position");
        	}else{
        		apiResultModel.setRet(apiResultModel.RET_SUCCESS);
        		apiResultModel.setErrorCode(apiResultModel.RET_SUCCESS);
        		apiResultModel.setLogined(this.isLogined());
        		apiResultModel.setData(map);
        		apiResultModel.setMsg("获取用户地理位置信息");
        	}
		} catch (Exception e) {
    	    e.printStackTrace();
    		logger.error("====================getUserPositionIsNow: get user position error :" + e.toString() + e.getCause(),e);
			apiResultModel.setRet(apiResultModel.RET_ERROR);
    		apiResultModel.setErrorCode(apiResultModel.RET_ERROR);
    		apiResultModel.setData("");
    		apiResultModel.setMsg("系统运行异常");
    		logger.error("获取地理位置信息异常：",e);
		}
        apiResultModel.setLogined(isLogined());
    	return ResponseTools.CallBackResultJsonP(JsonTools.jsonSer(apiResultModel), callback); 
    }
    
    /**
     * 获取用户信息生成 临时的二维码
     *  QRCodeType meal 表示餐券 二维码  account  个人储值卡 card 包月卡
     * @return
     */
    @ResponseBody
    @RequestMapping("/get_user_data_qrcode")
    public String getUserDataQRCode(HttpServletRequest request, HttpServletResponse response) {
    	ApiResultModel<Object> apiResultModel = new ApiResultModel<Object>(isLogined());
    	String callback = RequestTools.RequestString(request, "callback", "");
    	Map<String,Object> resultMap = null;
    	Integer userId  = this.getUserId();
    	String QRCodeType = RequestTools.RequestString(request, "QRCodeType", "account");
    	if(userId == null || userId == 0) {
    		
    		apiResultModel.setLogined(isLogined());
    		apiResultModel.setRet(apiResultModel.RET_ERROR);
    		apiResultModel.setErrorCode(apiResultModel.RET_ERROR);
    		apiResultModel.setData("");
    		apiResultModel.setMsg("请先登录");
    		return ResponseTools.CallBackResultJsonP(JsonTools.jsonSer(apiResultModel), callback); 
    		
    	}
    	
    	try {
    		resultMap = userService.getUserDataQRCode( userId, QRCodeType);
    		apiResultModel.setData(resultMap);
    		
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("====================getUserPositionIsNow: get user position error :" + e.toString() + e.getCause(),
					e);
			apiResultModel.setRet(apiResultModel.RET_ERROR);
			apiResultModel.setErrorCode(apiResultModel.RET_ERROR);
			apiResultModel.setData("");
			apiResultModel.setMsg("系统运行异常");
			logger.error("获取地理位置信息异常：", e);
			
		}
    	
    	return ResponseTools.CallBackResultJsonP(JsonTools.jsonSer(apiResultModel), callback);
    }
    
    /**
     * 获取用户信息
     * 包括餐券主要用于 给予管理员销餐
     * @return
     */
    @ResponseBody
    @RequestMapping("/get_user_data")
    public String getUserInfoData(HttpServletRequest request, HttpServletResponse response) {
    	ApiResultModel<Object> apiResultModel = new ApiResultModel<Object>(isLogined());
    	String callback = RequestTools.RequestString(request, "callback", "");
    	Map<String,Object> resultMap = null;
    	Integer userId  = RequestTools.RequestInt(request, "userId", 0);
    	String QRCodeType = RequestTools.RequestString(request, "QRCodeType", "account");
    	if(userId == null || userId == 0) {
    		
    		apiResultModel.setLogined(isLogined());
    		apiResultModel.setRet(apiResultModel.RET_ERROR);
    		apiResultModel.setErrorCode(apiResultModel.RET_ERROR);
    		apiResultModel.setData("");
    		apiResultModel.setMsg("参数错误未获取到用户ID");
    		return ResponseTools.CallBackResultJsonP(JsonTools.jsonSer(apiResultModel), callback); 
    		
    	}
    	UserInfo adminMealUserInfo = this.getUserInfo();
    	// 管理员未登录 
		if (adminMealUserInfo == null ) {

			apiResultModel.setLogined(isLogined());
			apiResultModel.setRet(apiResultModel.RET_ERROR);
			apiResultModel.setErrorCode(apiResultModel.RET_ERROR);
			apiResultModel.setData("");
			apiResultModel.setMsg("参数错误未获取到用户ID");
			return ResponseTools.CallBackResultJsonP(JsonTools.jsonSer(apiResultModel), callback);

		}

    	try {
    		resultMap = userService.getUserInfoAndUserMealData(userId, adminMealUserInfo, QRCodeType);
    		apiResultModel.setData(resultMap);
    		
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("====================getUserPositionIsNow: get user position error :" + e.toString() + e.getCause(),
					e);
			apiResultModel.setRet(apiResultModel.RET_ERROR);
			apiResultModel.setErrorCode(apiResultModel.RET_ERROR);
			apiResultModel.setData("");
			apiResultModel.setMsg("系统运行异常");
			logger.error("获取地理位置信息异常：", e);
			
		}
    	
    	return ResponseTools.CallBackResultJsonP(JsonTools.jsonSer(apiResultModel), callback);
    }
    
    
    /**
     * 获取用户权限
     * @return
     */
    @ResponseBody
    @RequestMapping("/get_user_role_list")
    public String getUserRoleList(HttpServletRequest request, HttpServletResponse response) {
    	ApiResultModel<Object> apiResultModel = new ApiResultModel<Object>(isLogined());
    	String callback = RequestTools.RequestString(request, "callback", "");
    	Map<String,Object> resultMap = null;
    	
    	UserInfo userInfo = this.getUserInfo();
    	
    	if(userInfo == null) {
    		apiResultModel.setLogined(isLogined());
    		apiResultModel.setRet(ApiResultModel.RET_ERROR);
    		apiResultModel.setErrorCode(ErrorCodeConstants.Code.USER_NOT_LOGIN.getCode());
    		apiResultModel.setMsg(ErrorCodeConstants.Code.USER_NOT_LOGIN.getMessage());
    		return ResponseTools.CallBackResultJsonP(JsonTools.jsonSer(apiResultModel), callback); 
    		
    	}
    	
    	
    	try {
    		
    		userService.bindingPresaleTeam(userInfo);
			resultMap = userService.querySysUserRoleList(userInfo);
			
			if(resultMap == null) {
				apiResultModel.setRet(apiResultModel.RET_ERROR);
				apiResultModel.setErrorCode(ErrorCodeConstants.Code.NOT_SYSTEM_USER.getCode());
				apiResultModel.setMsg(ErrorCodeConstants.Code.NOT_SYSTEM_USER.getMessage());
				return ResponseTools.CallBackResultJsonP(JsonTools.jsonSer(apiResultModel), callback);
			}
			apiResultModel.setData(resultMap);
			apiResultModel.setMsg("查询成功！");
			
		} catch (Exception e) {

			logger.error("UserController | getUserRoleList |  error :" + e.toString() + e.getCause(),e);
			apiResultModel.setRet(apiResultModel.RET_ERROR);
			apiResultModel.setErrorCode(apiResultModel.RET_ERROR);
			apiResultModel.setMsg("系统运行异常");
			
		}
    	apiResultModel.setLogined(isLogined());
    	return ResponseTools.CallBackResultJsonP(JsonTools.jsonSer(apiResultModel), callback);
    }

    /**
     * @Author: timo
     * @Date: 2018/11/6 20:19
     * @Description: 更新用户姓名
     * @param userId 用户Id
     * @param userName 用户真实姓名
     * @param operateType 操作类型 1 自己更新 不需要做权限校验 2 他人更新 需要做权限校验
     */
    @ResponseBody
    @RequestMapping("/update_user_name")
    public String updateUserName(HttpServletRequest request,
                                 HttpServletResponse response,
                                 Integer userId,
                                 String userName,
                                 Integer operateType){

        ApiResultModel<Object> apiResultModel = new ApiResultModel<Object>(isLogined());
        String callback = RequestTools.RequestString(request, "callback", "");

        try {
            apiResultModel = userService.updateUserName(userId,userName,this.getUserInfo(),operateType);
        }catch (Exception e){
            logger.error("UserController | updateUserName |  error :" + e.toString() + e.getCause(),e);
            apiResultModel.setRet(ApiResultModel.RET_ERROR);
            apiResultModel.setErrorCode(ErrorCodeConstants.Code.SYSTEM_ERROR_EXCEPTION.getCode());
            apiResultModel.setMsg("系统运行异常");
        }
        apiResultModel.setLogined(this.isLogined());
        return ResponseTools.CallBackResultJsonP(JsonTools.jsonSer(apiResultModel), callback);
    }
    
}
